package com.livenativern.webview;
/*
 *  @创建者    lihaijun
 *  @创建时间   2018/5/2 16:02
 *  @描述     ${TODO}
 *
 *  @更新者    $Author
 *  @更新时间   $Date
 *  @更新描述   ${TODO}
 */

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.livenativern.javascript.Lateralinterface;
import com.livenativern.javascript.LoginSucinterface;
import com.livenativern.utils.ProductUtils;
import com.livenativern.utils.SpUtils;

import java.io.File;

public class ReactWebViewManager extends SimpleViewManager<WebView> implements Lateralinterface.UpdateUi, Lateralinterface.Loginout {

    private static final String TAG                = "ReactWebViewManager";
    public static final  String REACT_CLASS        = "AndroidWebView";
    private static final String APP_CACAHE_DIRNAME = "/webcache";
    private static final String EVENT_NAME         = "LOGOUT";
    private WebView mWebView;
    private ThemedReactContext mContext;
    //    private String  mToken;
    private String  mDomain;

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    protected WebView createViewInstance(ThemedReactContext reactContext) {
        this.mContext = reactContext;
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
        mWebView = new WebView(reactContext);
        mWebView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        //        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//这里要设置为不适用缓存但是下面数据库路径要设置下可以清除缓存

        //        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式 （这种情况的意思视情况来决定是否使用缓存）
        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        //开启 database storage API 功能
        webSettings.setDatabaseEnabled(true);
        String cacheDirPath = reactContext.getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        //      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
        //        Log.i(TAG, "cacheDirPath="+cacheDirPath);
        //设置数据库缓存路径
        webSettings.setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        webSettings.setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        webSettings.setAppCacheEnabled(true);

        //下面三个最常用，基本都需要设置
        //        setCacheMode 设置缓存的模式 eg: settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //        setJavaSciptEnabled 设置是否支持Javascript eg: settings.setJavaScriptEnabled(true);
        //        setDefaultTextEncodingName 设置在解码时使用的默认编码 eg: settings.setDefaultTextEncodingName(“utf-8”);
        //        setAllowFileAccess 启用或禁止WebView访问文件数据
        //        setBlockNetworkImage 是否显示网络图像
        //        setBuiltInZoomControls 设置是否支持缩放
        //        setDefaultFontSize 设置默认的字体大小
        //        setFixedFontFamily 设置固定使用的字体
        //        setLayoutAlgorithm 设置布局方式
        //        setLightTouchEnabled 设置用鼠标激活被选项
        //        setSupportZoom 设置是否支持变焦

        //        webView.setWebChromeClient(new WebChromeClient());
        String userAgent = mWebView.getSettings().getUserAgentString();//找到webview的useragent
        //在useragent上添加APP_WEBVIEW 标识符,服务器会获取该标识符进行判断
        String key = userAgent.replace("Android", "iris" + "_" + ProductUtils.getAppcode(reactContext));
        mWebView.getSettings().setUserAgentString(key);


        //暴露js侧滑动，java暴露方法然后显示隐藏

        mWebView.addJavascriptInterface(new Lateralinterface(this), "wst");
        mWebView.addJavascriptInterface(new LoginSucinterface(reactContext), "log");
        return mWebView;
    }

    @ReactProp(name = "para")
    public void setPara(WebView webView, @Nullable ReadableMap para) {
        //        Log.e("TAG", "setUrl");
        //        view.loadUrl(url);
        if (para != null) {
            String url = para.getString("url");
            String domain = para.getString("domain");
            synCookies(SpUtils.getToken(mContext), domain, url, mContext);//同步token
            webView.loadUrl(url);
        }
    }


    /*@ReactProp(name = "domain")
    public void setDomain(WebView webView, @Nullable String domain) {
        //        Log.e("TAG", "setUrl");
        //        view.loadUrl(url);
        this.mDomain = domain;
    }*/

    private void synCookies(String token, String domain, String url, Context context) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();// 移除  
        cookieManager.removeAllCookie();
        StringBuilder sbCookie = new StringBuilder();
        sbCookie.append(String.format("e_token=%s", token));
        //        sbCookie.append(String.format("e_token=%s",SpUtils.getToken(context)));
        //        String domain=SpUtils.getCookie(MainActivity.this).split(";")[1].split(";")[1].split(";")[1].split(";")[0].split("=")[1];
        //        MyLogUtils.info("domain"+domain);
        //        sbCookie.append(String.format(";domain=%s","iris.com"));
        sbCookie.append(String.format(";domain=%s", domain));
        sbCookie.append(String.format(";path=%s", "/"));
        String cookieValue = sbCookie.toString();
        cookieManager.setCookie(url, cookieValue);//为url设置cookie    
        CookieSyncManager.getInstance().sync();//同步cookie  
    }

    /**
     * 清除WebView缓存
     */
    public void clearWebViewCache(Context context) {

        //清理Webview缓存数据库
        try {
            context.deleteDatabase("webview.db");
            context.deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebView 缓存文件
        File appCacheDir = new File(context.getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME);
        //        Log.e(TAG, "appCacheDir path="+appCacheDir.getAbsolutePath());

        File webviewCacheDir = new File(context.getCacheDir().getAbsolutePath() + "/webviewCache");
        //        Log.e(TAG, "webviewCacheDir path="+webviewCacheDir.getAbsolutePath());

        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }


    @Override
    public void showOrhide(String type) {

    }

    @Override
    public void loginoutact() {
        SpUtils.clearSp(mContext);
        nativeCallRn(mContext, "");
        //        finish();
        //        openActivity(LoginAct.class);
    }

    /**
     * Native调用RN
     *
     * @param msg
     */
    public void nativeCallRn(ReactContext context, String msg) {
        context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(EVENT_NAME, msg);
    }
}


